package com.think.admin.web.service.impl;

import com.think.admin.cons.AdminCons;
import com.think.admin.model.dto.role.RoleResourceDTO;
import com.think.admin.web.mapper.RoleResourceMapper;
import com.think.admin.web.service.IRoleResourceService;
import com.think.common.enums.StateEnum;
import com.think.common.exception.SysException;
import com.think.common.utils.SysUtils;
import com.think.common.web.service.impl.SuperServiceImpl;
import com.think.dao.entity.RoleResource;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * <p>
 * 角色资源表 服务实现类
 * </p>
 *
 * @author xwj
 * @since 2019-04-08
 */
@Service
@Transactional(rollbackFor = SysException.class)
@RequiredArgsConstructor
public class RoleResourceServiceImpl extends SuperServiceImpl<RoleResourceMapper, RoleResource> implements IRoleResourceService {
    private final RedissonClient redissonClient;

    @PostConstruct
    @Override
    public void resetRoleResource() {
        // 从缓存中删除角色资源信息
        redissonClient.getKeys().deleteByPattern(AdminCons.Redis.ROLE_RESOURCE + "*");

        // 重新构造角色-资源数据缓存
        List<RoleResourceDTO> roleResourceTrees = baseMapper.selectRoleResource(StateEnum.ENABLE);
        roleResourceTrees.forEach(roleResourceTree -> {
            if (SysUtils.isEmpty(roleResourceTree.getRoleId()) || SysUtils.isEmpty(roleResourceTree.getId())) {
                return;
            }
            redissonClient.getMap(AdminCons.Redis.ROLE_RESOURCE + roleResourceTree.getRoleId())
                    .put(roleResourceTree.getId(), roleResourceTree);
        });
    }
}
